package cn.ycc1.boot3compress.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author ycc
 * @date 2023/11/26
 */
@Slf4j
@RestController
public class TestController {
    @GetMapping("/test")
    public String test() {
        String[] imagePaths = {"/static/images/food_000.jpg", "/static/images/food_001.jpg", "/static/images/food_002.jpg"};
        String zipFilePath = "C:\\home\\test\\output2.zip";

        Path outputPath = Paths.get(zipFilePath);
        try (ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(new FileOutputStream(outputPath.toFile()))) {
            for (String imagePath : imagePaths) {
                Resource resource = new ClassPathResource(imagePath);
                try (BufferedInputStream inputStream = new BufferedInputStream(resource.getInputStream())) {
                    String entryName = resource.getFilename();
                    ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName);
                    zipOutput.putArchiveEntry(zipEntry);
                    IOUtils.copy(inputStream, zipOutput);
                    zipOutput.closeArchiveEntry();
                }
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "hello test2";
    }
}
